/*
@author: user
@date: 2022/6/30 10:41
@Version: 1.0
@last modifined by : user
@last Modifined time : 2022/6/30 10:41
*/

import { useRef, useState, useEffect } from 'react';

/** useStateWithCall方法说明
* @author: JasonStandFor
* @description Desc:: 一个强化版 useState. 用于批处理
* @param {any} initValue - 接收一个任意类型变量
* @example:
  // 引入 useStateWithCall
  const [test,setTest] = useStateWithCall(-1);
  // 设置新数据
  setTest(1, (newState) => {
    console.log(`新值${newState}`);
  });
* @return [initValue, newValueCallBackFunction]
* */
const useStateWithCall = (initValue) => {
  const ref = useRef(0);
  const callFRef = useRef();
  const setFuncRef = useRef();
  // TODO: 这里不使用 let 的原因是数据走向尽可能规范化，保持一致，不可随意修改数据类型
  const [state, setState] = useState(initValue);

  if (!ref.current) {
    ref.current = 1;
    setFuncRef.current = (newData, callF) => {
      callFRef.current = callF;
      setState(newData);
      return Promise.resolve(newData);
    };
  }

  useEffect(() => {
    callFRef.current?.(state);
  }, [state]);

  return [state, setFuncRef.current];
}

export default useStateWithCall;
